/**
 * @Title:  AuthMechanismActivity.java 
 * @Copyright:  XXX Co., Ltd. Copyright YYYY-YYYY,  All rights reserved 
 * @Description:  TODO<请描述此文件是做什么的> 
 * @author:  MeiYi 
 * @data:  2016-1-5 上午11:24:06 
 * @version:  V1.0 
 */

package artid.com.arttogo.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.media.AudioManager;
import android.media.AudioManager.OnAudioFocusChangeListener;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebSettings.LayoutAlgorithm;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

import artid.com.arttogo.R;
import artid.com.arttogo.adapter.ArtCollectorsAdapter;
import artid.com.arttogo.bean.ShareItem;
import artid.com.arttogo.bean.UpdataSystemMessageParser;
import artid.com.arttogo.db.Cache;
import artid.com.arttogo.network.AppUrl;
import artid.com.arttogo.network.AppUtil;
import artid.com.arttogo.network.VolleyBasic;
import artid.com.arttogo.network.VolleyCallback;
import artid.com.arttogo.network.VolleyData;
import artid.com.arttogo.network.VolleyMap;
import artid.com.arttogo.utils.ToastUtil;

/**
 * TODO<请描述这个类是干什么的>
 * 
 * @author 熊彬
 * @data: 2016-1-5 上午11:24:06
 * @version: V1.0
 */
public class WebViewActivity extends BaseActivity {
	private Context mContext;
	private WebView mWebView;
	private ArtCollectorsAdapter adapter;
	private ImageView share;
	View back;
	private TextView title;
	String id;
	String type;
	private RelativeLayout loading;
	ShareItem si;

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.sigmatrix.artworkart.BaseActivity#onCreate(android.os.Bundle)
	 */
	@SuppressLint("SetJavaScriptEnabled")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_webview);
		mContext = WebViewActivity.this;
		mWebView = (WebView) findViewById(R.id.webview);
		back = (View) findViewById(R.id.rela_back);
		title = (TextView) findViewById(R.id.tv_title);
		share = (ImageView) findViewById(R.id.iv_share);
		loading = (RelativeLayout) findViewById(R.id.rel_progressbar);
		loading.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				System.out.println("#zhebiceng");
			}
		});
		loading.setVisibility(View.VISIBLE);
		back.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				finish();
			}
		});
		si = (ShareItem) getIntent().getSerializableExtra("share");
		// System.out.println(si.toString());
		share.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				System.out.println("si.getImageUrl()=" + si.getImageUrl());
				if (TextUtils.isEmpty(si.getContent())) {
					si.setContent(si.getTitle());
				}
				AppUtil.showShare(mContext, si.getTitle(), si.getContent(),
						si.getImageUrl(), si.getUrl());
			}
		});
		try {
			id = si.getId();
		} catch (Exception e) {
			// TODO: handle exception
		}
		System.out.println("id=" + id);
		type = getIntent().getStringExtra("type");
		if (type.equals(AppUrl.LOAD_HOMEPAGE_WEB)
				|| type.equals(AppUrl.SYSTEMMESSAGE)) {
			share.setVisibility(View.INVISIBLE);
		}
		// String title = getIntent().getStringExtra("title");
		mWebView.getSettings().setJavaScriptEnabled(true);
		mWebView.getSettings().setDefaultTextEncodingName("UTF-8");
		mWebView.getSettings().setUseWideViewPort(true);
		mWebView.getSettings().setLoadWithOverviewMode(true);
		mWebView.getSettings()
				.setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
//		mWebView.setWebViewClient(new MyWebViewClient());
		mWebView.setWebChromeClient(new WebChromeClient() {
			public void onProgressChanged(WebView view, int progress) {
				// Activity和Webview根据加载程度决定进度条的进度大小
				// 当加载到100%的时候 进度条自动消失
				// WebViewProgressActivity.this.setTitle("Loading...");
				// WebViewProgressActivity.this.setProgress(progress * 100);
				if (progress == 100) {
					loading.setVisibility(View.GONE);
					// WebViewProgressActivity.this.setTitle("完成");
				}
			}

			/*
			 * (non-Javadoc)
			 * 
			 * @see
			 * android.webkit.WebChromeClient#onReceivedTitle(android.webkit
			 * .WebView, java.lang.String)
			 */
			@Override
			public void onReceivedTitle(WebView view, String titleT) {
				// TODO Auto-generated method stub
				super.onReceivedTitle(view, titleT);
			}
		});
		loadWebView();
		// requestGradeList();
	}

	String url;

	/**
	 * 
	 */
	AudioManager audioManager;
	OnAudioFocusChangeListener listener;

	private void loadWebView() {
		// TODO Auto-generated method stub
		
		if (type.equals(AppUrl.AUTH_NEWS)) {
			title.setText("资讯详情");
			url = Cache.base+"h5/forensic-news.php?id=" + id;
			si.setUrl(url);
		} else if (type.equals(AppUrl.AUCTION_DYNAMEICS)) {
			title.setText("拍卖详情");
//			url = Cache.basewebUrl+"h5/auction-dynamics.html?id=" + id;
		} else if (type.equals(AppUrl.EXHIBITION)) {
			title.setText(getIntent().getExtras().getString("title"));
			url =getIntent().getStringExtra("url");
		} else if (type.equals(AppUrl.GALLERISE)) {
			title.setText(si.getTitle());
//			url = "http://124.193.95.86:28180/h5/exhibi/tion-hall.html?id=" + id;
			url = Cache.base+"h5/exhibition-hall.php?id=" + id;
			si.setUrl(url);
		} else if (type.equals(AppUrl.LOAD_HOMEPAGE_WEB)) {
			url = getIntent().getExtras().getString("url");
			isSetWebTitle = true;
			// title.setText(si.getTitle());
		} else if (type.equals(AppUrl.SYSTEMMESSAGE)) {
			updataSystmeMessage(getIntent().getStringExtra("messageID"));
			return;
		} else if (type.equals(AppUrl.ART_HALL)) {
			url = getIntent().getExtras().getString("url");
			isSetWebTitle = true;
		}else if (type.equals(AppUrl.LOAD_WEB_WITH_TITLE)) {
			url = getIntent().getExtras().getString("url");
			title.setText(getIntent().getExtras().getString("title"));
			share.setVisibility(View.INVISIBLE);
		}else if(type.equals(AppUrl.ART_HALL_QJ)){
			title.setText(getIntent().getExtras().getString("title"));
			url =getIntent().getStringExtra("url");
			 if(getRequestedOrientation()!= ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE){
				  setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
				 }
		}
		
		System.out.println("url=" + url);
		WebSettings webSettings = mWebView.getSettings();
		webSettings.setJavaScriptEnabled(true);
		mWebView.setWebViewClient(new WebViewClient() {
			@Override
			public boolean shouldOverrideUrlLoading(WebView view, final String url) {
				  if (url.startsWith("tel:")){
					  AlertDialog dialog = new AlertDialog.Builder(WebViewActivity.this).setTitle("提示")
								.setMessage("是否拨打电话？").setPositiveButton("确定", new DialogInterface.OnClickListener() {
									
									@Override
									public void onClick(DialogInterface arg0, int arg1) {
										// TODO Auto-generated method stub
										Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse(url));
										WebViewActivity.this.startActivity(intent);
									}
								}).setNegativeButton("取消", null).show();
	                  } else if(url.startsWith("http:") || url.startsWith("https:")) {
	                      view.loadUrl(url);
	                  }
				return true;
			}
			@Override
			public void onPageFinished(WebView view, String url) {
				// TODO Auto-generated method stub
				super.onPageFinished(view, url);
				String strtitle = view.getTitle();
				// if (strtitle.length()>7) {
				// strtitle = strtitle.substring(0,7)+"..";
				// }
				if (isSetWebTitle) {
					title.setText(strtitle);
				}
				if (type.equals(AppUrl.ART_HALL_QJ)) {
					isSetWebTitle = true;
				}
				if (type.equals(AppUrl.AUTH_NEWS)) {
					title.setText("资讯详情");
				}
			}
		});
		mWebView.loadUrl(url);
	}

	Boolean isSetWebTitle = false;

//	private class MyWebViewClient extends WebViewClient {
//
//		/*
//		 * (non-Javadoc)
//		 * 
//		 * @see
//		 * android.webkit.WebViewClient#shouldOverrideUrlLoading(android.webkit
//		 * .WebView, java.lang.String)
//		 */
//		@Override
//		public boolean shouldOverrideUrlLoading(WebView view, final String url) {
//			// TODO Auto-generated method stub
//
//			  if (url.startsWith("tel:")){
//				  AlertDialog dialog = new AlertDialog.Builder(WebViewActivity.this).setTitle("提示")
//							.setMessage("是否拨打电话？").setPositiveButton("确定", new DialogInterface.OnClickListener() {
//								
//								@Override
//								public void onClick(DialogInterface arg0, int arg1) {
//									// TODO Auto-generated method stub
//									Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse(url));
//									startActivity(intent);
//								}
//							}).setNegativeButton("取消", null).show();
//                  } else if(url.startsWith("http:") || url.startsWith("https:")) {
//                      view.loadUrl(url);
//                  }
//			return true;
//		}
//
//		@Override
//		public void onPageFinished(WebView view, String url) {
//			// TODO Auto-generated method stub
//			super.onPageFinished(view, url);
//			String strtitle = view.getTitle();
//			// if (strtitle.length()>7) {
//			// strtitle = strtitle.substring(0,7)+"..";
//			// }
//			if (isSetWebTitle) {
//				title.setText(strtitle);
//			}
//			if (type.equals(AppUrl.AUTH_NEWS)) {
//				title.setText("资讯详情");
//			}
//		}
//
//	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
//		 if (audioManager!= null) {  
//	            audioManager.abandonAudioFocus(listener); 
//	            audioManager = null;  
//	        }  
	}
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		mWebView.reload();
		super.onPause();
		
//		if (type.equals(AppUrl.ART_HALL)) {
//			int i = 0;
//			do {
//				int result = audioManager.requestAudioFocus(listener,
//						AudioManager.STREAM_MUSIC,
//						AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
//
//				if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
//					break;
//				}
//				i++;
//			} while (i < 10);
//		}
	}

//	Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:"+ "010-64688820"));
//	startActivity(intent);
	
	/**
	 * 修改系统消息为已读
	 */

	private void updataSystmeMessage(final String MessageId) {
		VolleyBasic.getInstance(this).post(Cache.updateSystemread,
				VolleyMap.getInstance().updateSystemread(MessageId),
				UpdataSystemMessageParser.class, new VolleyCallback() {
					public void onSuccess(VolleyData vd) {
						// TODO Auto-generated method stub
						System.out.println(vd.getJson());
						UpdataSystemMessageParser bean = (UpdataSystemMessageParser) vd
								.getData();
						if ("1".equals(bean.getStatus())) {
							// 成功
							Intent intent0 = new Intent(
									"com.SystemMessage_Fragment.receiver");
							intent0.putExtra("WebViewActivity", true);
							mContext.sendBroadcast(intent0);
							title.setText("系统消息");
							url = getIntent().getExtras().getString("url");
							mWebView.loadUrl(url);
							Log.d("log", "修改推送状态：" + MessageId);
						} else if ("0".equals(bean.getStatus())) {
							// 失败
							ToastUtil.toast(mContext, "修改消息状态失败");
						}
					}

					public void onError(VolleyError volleyError) {
					}
				});
	}

	// private void requestGradeList() {
	// AppParser parser = new AppParser(AppItem.class);
	// // parser.setHttpUriRequest(AppUrl.newsContent());
	// parser.setHttpUriRequest(AppUrl.newsContent(id));
	// // parser.setHttpUriRequest(AppUrl.userLogin(mContext,"123123"));
	// ProtocolTask task = new ProtocolTask();
	// task.setOnProtocolTaskListener(mOnProtocolTaskListenerGradeList);
	// task.execute(parser);
	// }
	//
	// OnProtocolTaskListener mOnProtocolTaskListenerGradeList = new
	// OnProtocolTaskListener() {
	// @Override
	// public void onPostExecute(BasicParser parser) {
	// initDataGradeList((AppParser) parser);
	// }
	// };
	//
	// @SuppressWarnings("unchecked")
	// private void initDataGradeList(AppParser parser) {
	// if (!TextUtils.isEmpty(parser.getMsg())) {
	// Config.showTip(mContext, parser.getMsg());
	// }
	// if (parser.getCode() != BasicParser.Success) {
	// return;
	// }
	// }
}
